import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Card,
  Button,
  Input,
  Table,
  Form,
  Modal,
  Icon,
  Tooltip,
  TreeSelect,
  Divider,
  Popconfirm,
  Row,
  Col,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';

const FormItem = Form.Item;
const { Search, TextArea } = Input;
const { TreeNode } = TreeSelect;

const DeviceGroupForm = Form.create()(props => {
  const { modalVisible, form, options, current, handleModalVisible, handleAdd } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleAdd(fieldsValue, form);
    });
  };
  return (
    <Modal
      title={
        <span>
          <FormattedMessage id="app.dm.groups.add" />
          <em className={styles.optional}>
            <Tooltip
              title={
                <span>
                  <a href="###">
                    <FormattedMessage id="help.doc" />
                  </a>
                </span>
              }
            >
              <Icon type="info-circle-o" style={{ marginLeft: 4 }} />
            </Tooltip>
          </em>
        </span>
      }
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Form>
        <FormItem
          label={formatMessage({ id: 'app.dm.groups.info.parent' })}
          colon={false}
          style={{ width: 570 }}
        >
          <div>
            {form.getFieldDecorator(
              'pid',
              {},
            )(
              <TreeSelect
                showSearch
                style={{ width: 540 }}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                defaultValue="-1"
                treeDefaultExpandAll
                allowClear
              >
                <TreeNode value="-1" title="分组" key="-1">
                  {options}
                </TreeNode>
              </TreeSelect>,
            )}
            <Tooltip title={<FormattedMessage id="app.dm.groups.info.parent.help" />}>
              <Icon type="info-circle-o" style={{ marginLeft: 10 }} />
            </Tooltip>
          </div>
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.groups.info.name' })}
          colon={false}
          style={{ width: 570 }}
        >
          {form.getFieldDecorator('name', {
            rules: [
              { required: true, message: formatMessage({ id: 'app.dm.groups.info.name.place' }) },
            ],
          })(
            <div>
              <Input
                placeholder={formatMessage({ id: 'app.dm.groups.info.name.place' })}
                style={{ width: 540 }}
              />
              <Tooltip title={<FormattedMessage id="app.dm.groups.info.name.help" />}>
                <Icon type="info-circle-o" style={{ marginLeft: 10 }} />
              </Tooltip>
            </div>,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.groups.info.desc' })} colon={false}>
          {form.getFieldDecorator('desc', {
            rules: [],
            initialValue: current.desc,
          })(
            <TextArea
              rows={4}
              placeholder={formatMessage({ id: 'app.dm.groups.info.desc.place' })}
            />,
          )}
        </FormItem>
      </Form>
    </Modal>
  );
});

@connect(({ groups, loading }) => ({
  groups,
  loading: loading.models.groups,
}))
@Form.create()
class Groups extends PureComponent {
  state = {
    modalVisible: false,
  };

  columns = [
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.groups.table.name' }),
      dataIndex: 'name',
    },
    {
      key: 'code',
      title: formatMessage({ id: 'app.dm.groups.table.code' }),
      dataIndex: 'code',
    },
    {
      key: 'createTime',
      title: formatMessage({ id: 'app.dm.groups.table.createTime' }),
      dataIndex: 'createTime',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.groups.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleView(record.id)}>
            <FormattedMessage id="app.dm.groups.table.action.view" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280 }}>
                <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                  <span>{formatMessage({ id: 'app.dm.groups.del.confirm' })}</span>
                </div>
                <div>
                  <span>{formatMessage({ id: 'app.dm.groups.del.prompt' })}</span>
                </div>
              </div>
            }
            onConfirm={() => this.handleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.dm.groups.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'groups/init',
    });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleView = id => {
    router.push(`/dm/groups/detail/${id}`);
  };

  handleAdd = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'groups/add',
      payload: {
        ...fields,
      },
      form,
      handleModalVisible,
    });
  };

  handleDelete = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'groups/del',
      payload: id,
    });
  };

  render() {
    const {
      groups: { list, pagination, current, groupsOptions },
      loading,
      dispatch,
    } = this.props;

    const {
      form: { getFieldDecorator, getFieldsValue },
    } = this.props;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      onShowSizeChange(curr, size) {
        dispatch({
          type: 'groups/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: size } },
        });
      },
      onChange(curr) {
        dispatch({
          type: 'groups/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: pagination.currentSize } },
        });
      },
    };

    const search = value => {
      dispatch({
        type: 'groups/fetch',
        payload: { ...getFieldsValue(), ...{ name: value } },
      });
    };

    const refresh = () => {
      dispatch({
        type: 'groups/fetch',
        payload: { ...getFieldsValue() },
      });
    };

    const { modalVisible } = this.state;

    let options = [];
    if (groupsOptions) {
      options = groupsOptions.map(d => <TreeNode value={d.id} title={d.name} key={d.id} />);
    }

    const parentMethods = {
      options,
      current,
      handleModalVisible: this.handleModalVisible,
      handleAdd: this.handleAdd,
    };

    return (
      <PageHeaderWrapper title={formatMessage({ id: 'app.dm.groups.title' })}>
        <div className={styles.standardList}>
          <Form layout="inline">
            <Card bordered={false}>
              <div className={styles.extraContent}>
                <Row>
                  <Col span={12}>
                    {/* <span style={{fontSize:'16px',color:'rgba(0, 0, 0, 0.85)',fontWeight:500}}><FormattedMessage id="app.dm.groups.title" /></span> */}
                    <FormItem>
                      {getFieldDecorator('name')(
                        <Search
                          className={styles.extraContentSearch}
                          placeholder={formatMessage({ id: 'app.dm.groups.search' })}
                          onSearch={search}
                        />,
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12} style={{ textAlign: 'right' }}>
                    <FormItem>
                      <Button onClick={refresh}>
                        <FormattedMessage id="app.dm.product.refresh" />
                      </Button>
                    </FormItem>
                    <FormItem style={{ marginRight: 0 }}>
                      <Button
                        type="primary"
                        style={{ marginLeft: 8 }}
                        onClick={() => this.handleModalVisible(true)}
                      >
                        <FormattedMessage id="app.dm.groups.add" />
                      </Button>
                    </FormItem>
                  </Col>
                </Row>
                {/* <Row>
                  <FormItem>
                    {getFieldDecorator('name')(
                      <Search className={styles.extraContentSearch} placeholder={formatMessage({id:'app.dm.groups.search'})} onSearch={search} />
                    )}
                  </FormItem>
                </Row> */}
              </div>
              <Table
                columns={this.columns}
                dataSource={list}
                pagination={paginationProps}
                loading={loading}
                rowKey="id"
                style={{ marginTop: 15 }}
              />
            </Card>
          </Form>
        </div>
        <DeviceGroupForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default Groups;
